package com.crimax.lanproj.controller;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller  
public class PostController {  
	
		@Autowired
		private HttpServletRequest request;
		
		private @Autowired ServletContext servletContext;
	
        @RequestMapping(value = "/postController.do", method = RequestMethod.GET)  
        public @ResponseBody  
        void fetchFlowDowns(HttpServletResponse response) throws Exception {  

        response.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html");  
        PrintWriter writer = response.getWriter();
        
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6LcbhewSAAAAAHeoAPnk7rxh6eVT9gvk-0RpLSxe");
        

        
        
        String name = request.getParameter("name");       
        String email = request.getParameter("email");
        String message = request.getParameter("message");       
        String challenge = request.getParameter("recaptcha_challenge_field");       
        String uresponse = request.getParameter("recaptcha_response_field");
        
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (reCaptchaResponse.isValid()) {
        	try {
        	    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(servletContext.getRealPath("/WEB-INF/content/messages.txt"), true)));
        	    out.println("---------");
        	    out.println(name);
        	    out.println(email);
        	    out.println(message);
        	    out.close();
        	} catch (IOException e) {
        		e.printStackTrace();
        		writer.print("3");
        	}
        	writer.print("1");
        } else {
        	writer.print("2");
        }
       

    }  
}  